package com.xiaoshou.action;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class Suoyin {
	public static void main(String[] args) throws IOException, Exception {
		//delteOf();
		searchOf();
	}
	
	public static void searchOf() throws IOException, Exception{
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File("F:\\工作相关索引\\销售索引")));// 打开索引
		IndexSearcher searcher = new IndexSearcher(reader);
		
		Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_40);
		String[] fields = { "questionname" };
		Occur[] occurs = new Occur[] { Occur.SHOULD };
		Query query = MultiFieldQueryParser.parse(Version.LUCENE_40, "地址", fields,
				occurs, analyzer);
		TopDocs result = searcher.search(query, searcher.getIndexReader()
				.maxDoc());
		
		ScoreDoc[] hits = result.scoreDocs;
		for (int i = 0; i <= 0; i++) {
			System.out.println(searcher.doc(hits[i].doc));
		}
		analyzer.close();
		
		reader.close();
	}
	
	
	public static void delteOf(){
		IndexWriter writer = null;
		Analyzer sa = new SmartChineseAnalyzer(Version.LUCENE_40);
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, sa);
		Directory dir1 = null;
		try {
			dir1 = FSDirectory.open(new File("F:\\工作相关索引\\销售索引"));
			writer = new IndexWriter(dir1, iwc);
			Term term = new Term("id", "28d86232-2102-4557-90f4-9cbd0fbcfc0b");
			
			//Term term2 = new Term("questionname",);
			writer.deleteDocuments(term);
			writer.commit();
			writer.close();
		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(writer!=null){
					writer.close();
					sa.close();
				}
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
